package com.workflow.listener;

import com.gec.domain.Dept;
import com.gec.domain.Role;
import com.gec.domain.User;
import com.gec.service.LeaveService;
import com.gec.utils.MyWebUtils;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;

import java.util.Set;

/**
 * @author Aniki
 * @date  2021-12-2
 */
public class LeaveTaskHandler implements TaskListener {


    private LeaveService leaveService;

    public LeaveTaskHandler(){

        leaveService = MyWebUtils.getBean(LeaveService.class);
    }


    @Override
    public void notify(DelegateTask task) {
        /**取出当前登录系统的用户  从会话域中取出用户*/
        User curUser = MyWebUtils.getCurrentUser();

        /**获取当前用户的角色  暂且当做只有一个 以后有多个要修改*/
        Set<Role> roles = curUser.getRoles();
        Role role = roles.iterator().next();

        /**获取任务ID  流程实例ID*/
        String taskId = task.getId();
        String processInsId = task.getProcessInstanceId();

        Dept dept = curUser.getDept();
        String  leaderId = null;

        String roleName = role.getRoleName();
        if (roleName.equals("leader")) {
            leaderId = leaveService.getHigherDeptLeader(dept.getId());
        } else {
            /**调用service 去查当前部门的 Leader  */
            leaderId = leaveService.getDeptLeader(dept.getId());
        }
        /** 设置新建节点办理人 */
        task.setAssignee(leaderId);
        /**更新t_leave表    办理人+ 任务ID*/
        leaveService.updateAssigneeAndTask(processInsId,taskId,leaderId);


    }
}
